package com.nrgedge.magnolia;

import info.magnolia.module.ModuleLifecycle;
import info.magnolia.module.ModuleLifecycleContext;

import javax.servlet.http.HttpServletRequest;

import net.tanesha.recaptcha.ProxyReCaptchaImpl;
import net.tanesha.recaptcha.ReCaptchaResponse;

public class ReCaptchaModule implements ModuleLifecycle {

	private String privateKey;
	private String publicKey;
	private String proxyHost;
	private String proxyPort;
	private String proxyUsername;
	private String proxyPassword;
	
	private boolean fieldValidation = false;
	
	public void start(ModuleLifecycleContext moduleLifecycleContext) {

	}

	public void stop(ModuleLifecycleContext moduleLifecycleContext) {

	}

	public String getPrivateKey() {
		return privateKey;
	}

	public void setPrivateKey(String privateKey) {
		this.privateKey = privateKey;
	}

	public String getPublicKey() {
		return publicKey;
	}

	public void setPublicKey(String publicKey) {
		this.publicKey = publicKey;
	}

	public String getProxyHost() {
		return proxyHost;
	}

	public void setProxyHost(String proxyHost) {
		this.proxyHost = proxyHost;
	}

	public String getProxyPort() {
		return proxyPort;
	}

	public void setProxyPort(String proxyPort) {
		this.proxyPort = proxyPort;
	}

	public String getProxyUsername() {
		return proxyUsername;
	}

	public void setProxyUsername(String proxyUsername) {
		this.proxyUsername = proxyUsername;
	}

	public String getProxyPassword() {
		return proxyPassword;
	}

	public void setProxyPassword(String proxyPassword) {
		this.proxyPassword = proxyPassword;
	}
	
	public boolean isFieldValidation() {
		return fieldValidation;
	}

	public void setFieldValidation(boolean fieldValidation) {
		this.fieldValidation = fieldValidation;
	}
	
	public boolean validateRequest(final HttpServletRequest request) {
		final String remoteAddr = request.getRemoteAddr();    
        
        final String proxyHost = getProxyHost();
        final String proxyPort = getProxyPort();
        final String proxyUsername = getProxyUsername();
    	final String proxyPassword = getProxyPassword();
    	
    	final ProxyReCaptchaImpl reCaptcha = new ProxyReCaptchaImpl(proxyHost, proxyPort != null ? Integer.parseInt(proxyPort) : 0, proxyUsername, proxyPassword);
        
        reCaptcha.setPrivateKey(getPrivateKey());

        final String challenge = request.getParameter("recaptcha_challenge_field");
        final String uresponse = request.getParameter("recaptcha_response_field");
        final ReCaptchaResponse reCaptchaResponse = reCaptcha.checkAnswer(remoteAddr, challenge, uresponse);
    	
    	return reCaptchaResponse.isValid();
	}

}
